package com.weipai.education.utils;

import com.weipai.education.config.interceptor.LoginHandlerInterceptor;
import com.weipai.education.dao.UserDao;
import com.weipai.education.enums.SourceStatus;
import com.weipai.education.model.User;
import com.weipai.education.shiro.AppCacheDao;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * session管理对象
 */
@Component
public class SessionUserUtil {
    private static final Logger logger = LoggerFactory.getLogger(SessionUserUtil.class);

    @Autowired
    private LoginHandlerInterceptor loginHandlerInterceptor;

    @Autowired
    private AppCacheDao appCacheDao;
    @Autowired
    private UserDao userDao;
    
    /**
     * 获取登录用户信息
     */
    public User getUserAttr() {
        return getUser();
    }
    
    public User getUser() {

        User user = null;
        int type = loginHandlerInterceptor.getUserType();
        if (SourceStatus.MOVE.getType() == type) {
            String token = getAuthenticationToken();
            user = appCacheDao.getUser(token);
            if (user == null) {
                String mobile = PasswordHelper.getUserName(token);
                user = userDao.getUserByMobile(mobile);
                if (user != null) {
                    appCacheDao.save(token, user);
                }
            }
        }else{
            Session session = SecurityUtils.getSubject().getSession();
            user =  (User) session.getAttribute("loginUser");
        }
        return user;
    }

    public String getAuthenticationToken() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        return request.getHeader(LoginHandlerInterceptor.AUTH_TOKEN_HEADER);
    }

}
